﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using Common;

public partial class System_RoleSettings : PageBase
{
    public string PrivilegeItems = "", FunctionCategoryItems;
    public int CategoryCount = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Expires = -1;
        PageBegin("system role admin");
 
        if (RequestBase.GetQueryString("otype") == "modify")
        {

            txtRolsId.Value = RequestBase.GetQueryString("roleid").Trim();
            FunctionCategoryItems = FunctionsCategoryMenu();
        }

        if (RequestBase.GetFormString("otype") == "getprivileges")
        {   
            /// 角色权限XML数据集
            GetPrivilegesByRoleId();
        }

        /// 保存设置
        if (RequestBase.GetFormString("__EVENTTARGET").Trim().ToLower() == "saveinfo")
        {
            string res = "";
            if (RequestBase.GetQueryString("otype") == "modify")
            {
                /// 修改角色信息
                res = SaveRolesInfo();
                if (res == "succeeded" && RequestBase.GetFormString("__EVENTARGUMENT").Trim().ToLower() != "unchange")
                {
                    /// 设置角色权限
                    res = SetRolePrivileges(RequestBase.GetFormString("privilegeinfo").Trim(), RequestBase.GetQueryString("roleid"));
                }
            }
            else
            {
                /// 添加角色信息
                res = SaveRolesInfo();
            }

            switch (res)
            {
                case "succeeded":
                    if (RequestBase.GetQueryString("otype") == "modify")
                    {
                        JScript.AlertAndReturnValueToParent("Successfully set!", "window.opener.document.getElementById(\"RefreshItems\").click(); window.close();");
                    }
                    else
                    {
                        JScript.AlertAndReturnValueToParent("Successfully set!", "window.opener.document.getElementById(\"RefreshItems\").click(); window.close();");
                    }
                    break;
                case "已存在!":
                    JScript.Alert("The name has exists!");
                    break;
                default:
                    JScript.Alert(res);
                    break;
            }
        }

        if (!IsPostBack)
        {
            if (RequestBase.GetQueryString("otype") == "modify")
            {
                InitializeRoleInfo();
            }
            else
                spanRoleName.InnerHtml = "新增角色";
        }
    }

    #region 权限信息显示
    public string FunctionsCategoryMenu()
    {
        StringBuilder _tabHTML = new StringBuilder();
        StringBuilder _divHTML = new StringBuilder();

        string _tab = "<li class=\"ms-crm-Tab {1}\" id=\"tab{0}Tab\" tabindex=\"-1\" tabid=\"tab{0}\"><a onclick=\"return false;\" href=\"javascript:onclick();\" target=\"_self\">{2}</a></li>";
        string _div = "<div class=\"ms-crm-Tab\" id=\"tab{0}\" style=\"overflow-y: auto; display: {1}\"><table height=\"auto\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\"><tbody>{2}</tbody></table></div>";
        int i = 1;

        DataTable dt = BLL.CommonBLL.Select("[System_FunctionCategory]", "FunctionCategoryId, CategoryName", " ORDER BY LineNum ASC");
        foreach (DataRow dr in dt.Select(""))
        {
            CategoryCount = i;
            if (i == 0)
            {
                _tabHTML.Append(string.Format(_tab, i.ToString(), "class=\"ms-crm-Tab-Selected\"", dr[1].ToString()));
                _divHTML.Append(string.Format(_div, i.ToString(), "inline;", GetFunctinsByCategoryId(dr[0].ToString())));
            }
            else
            {
                _tabHTML.Append(string.Format(_tab, i.ToString(), "", dr[1].ToString()));
                _divHTML.Append(string.Format(_div, i.ToString(), "none;", GetFunctinsByCategoryId(dr[0].ToString())));
            }
            i++;
        }
        dt.Clear();
        dt.Dispose();
        PrivilegeItems = _divHTML.ToString();
        return _tabHTML.ToString();
    }
    /// <summary>
    /// 匹配模块类别ID, 获取模块Html数据
    /// </summary>
    public string GetFunctinsByCategoryId(string categoryId)
    {
        string items = "<tr><td class=\"ms-crm-Form-Section ms-crm-Form-SectionBar\" colspan=\"9\">{0}</td></tr>{1}<tr height=\"20\"><td>&nbsp;</td></tr>";
        StringBuilder _trHTML = new StringBuilder();

        DataTable dt = BLL.CommonBLL.Select("[System_FunctionBase]", "FunctionID, FunctionName", " AND FunctionCategoryId = '" + categoryId.Trim() + "'");

        foreach (DataRow dr in dt.Select(""))
        {
            _trHTML.Append(string.Format(items, dr[1].ToString(), GetPrivilegesByFunctionId(dr[0].ToString()), dr[0].ToString()));
        }

        dt.Clear();
        dt.Dispose();

        return _trHTML.ToString();

    }
    /// <summary>
    /// 匹配模块类别获取权限ID
    /// </summary>
    public string GetPrivilegesByFunctionId(string functionId)
    {
        string _tr = "<tr><td valign=\"top\">";
        _tr += "<table onmouseover=\"SetAltText();\" style=\"table-layout: fixed; border-bottom: #dddddd 1px solid;\" onclick=\"ProcessClick();\" cellspacing=\"0\" cellpadding=\"2\" width=\"100%\">";
        _tr += "<colgroup><col width=\"100\"><col width=\"70\"><col width=\"70\"><col width=\"100\"><col width=\"70\"><col width=\"70\"><col width=\"100\"><col width=\"70\"><col></colgroup><tbody>{0}";
        _tr += "</tbody></table></td></tr>";

        string title = "<td>{0}</td>";
        string items = "{4}<td class=\"BizRolesedit_td_r\"><img class=\"i\" id=\"roles_{0}\" alt=\"\" p=\"{1}\" otn=\"\" m=\"1\" x=\"16\" d=\"{2}\" b=\"{3}\" l=\"{7}\" linenum=\"{5}\" ischange=\"0\" name=\"{6}\"></td><td>&nbsp;</td>";

        string _titleHTML = "";

        StringBuilder _trHTML = new StringBuilder();

        DataTable dt = BLL.CommonBLL.Select("[System_FunctionPrivilegeBase]", "PrivilegeId, PrivilegeName, LineNum, CanBeDeep", " AND FunctionId = '" + functionId + "'");

        int count = dt.Rows.Count / 3;
        count++;
        bool colorBl = true;

        for (int num = 0; num < count; num++)
        {

            colorBl = (!colorBl);

            StringBuilder _itemHTML = new StringBuilder();
            int a = num + 1;
            a = a * 3;
            if (a < dt.Rows.Count + 1)
            {
                a = 3;
                if (colorBl)
                {
                    _itemHTML.Append("<tr class=\"on\">");
                }
                else
                {
                    _itemHTML.Append("<tr>");
                }
                for (int i = 0; i < a; i++)
                {
                    int dtcount = num * 3 + i;
                    _titleHTML = string.Format(title, dt.Rows[dtcount]["PrivilegeName"].ToString());
                    _itemHTML.Append(string.Format(items, dt.Rows[dtcount]["PrivilegeId"].ToString(), i.ToString(), 1, dt.Rows[dtcount]["PrivilegeId"].ToString(), _titleHTML, dt.Rows[dtcount]["LineNum"].ToString(), functionId, dt.Rows[dtcount]["CanBeDeep"].ToString().Replace("True", "23").Replace("False", "16")));
                }
                _itemHTML.Append("</tr>");
                _trHTML.Append(string.Format(_tr, _itemHTML.ToString()));
            }
            else
            {
                a = dt.Rows.Count + 3 - a;
                if (a != 0)
                {
                    if (colorBl)
                    {
                        _itemHTML.Append("<tr class=\"on\">");
                    }
                    else
                    {
                        _itemHTML.Append("<tr>");
                    }
                    for (int i = 0; i < a; i++)
                    {
                        int dtcount = num * 3 + i;
                        _titleHTML = string.Format(title, dt.Rows[dtcount]["PrivilegeName"].ToString());
                        _itemHTML.Append(string.Format(items, dt.Rows[dtcount]["PrivilegeId"].ToString(), i.ToString(), 1, dt.Rows[dtcount]["PrivilegeId"].ToString(), _titleHTML, dt.Rows[dtcount]["LineNum"].ToString(), functionId, dt.Rows[dtcount]["CanBeDeep"].ToString().Replace("True", "23").Replace("False", "16")));
                    }
                    for (int j = 0; j < 3 - a; j++)
                    {
                        _itemHTML.Append("<td>&nbsp;</td><td class=\"BizRolesedit_td_r\">&nbsp;</td><td>&nbsp;</td>");
                    }
                    _itemHTML.Append("</tr>");
                    _trHTML.Append(string.Format(_tr, _itemHTML.ToString()));

                }
            }
        }

        dt.Clear();
        dt.Dispose();

        return _trHTML.ToString();
    }
    #endregion

    #region 设置角色权限
    string SetRolePrivileges(string rolesPrivileges, string roleid)
    {
        rolesPrivileges += "#";
        rolesPrivileges = rolesPrivileges.Replace("|#", "");

        DataTable table = new DataTable("PrivilegesData");
        DataRow Dr;
        DataColumn Dc1 = new DataColumn("Index", typeof(System.Int16));
        DataColumn Dc2 = new DataColumn("PrivilegeDepth", typeof(System.String));
        DataColumn Dc3 = new DataColumn("PrivilegeId", typeof(System.String));
        DataColumn Dc4 = new DataColumn("FunctionId", typeof(System.String));
        DataColumn Dc5 = new DataColumn("RoleId", typeof(System.String));
        DataColumn Dc6 = new DataColumn("LineNum", typeof(System.String));
        table.Columns.Add(Dc1);
        table.Columns.Add(Dc2);
        table.Columns.Add(Dc3);
        table.Columns.Add(Dc4);
        table.Columns.Add(Dc5);
        table.Columns.Add(Dc6);

        string[] arrPrivileges = rolesPrivileges.Split('|');
        for (int i = 0; i < arrPrivileges.Length; i++)
        {
            Dr = table.NewRow();
            Dr[0] = i + 1;
            Dr[1] = arrPrivileges[i].Split(';')[1];
            Dr[2] = arrPrivileges[i].Split(';')[0];
            Dr[3] = arrPrivileges[i].Split(';')[2];
            Dr[4] = roleid;
            Dr[5] = arrPrivileges[i].Split(';')[3];
            table.Rows.Add(Dr);
        }
        string result = BLL.SystemRoles.RolesSettings(table, roleid);
        table.Dispose();

        return result;
    }

    /// <summary>
    /// 匹配角色 ID, 获取所持模块权限数据
    /// </summary>
    public void GetPrivilegesByRoleId()
    {
        DataTable dat = BLL.SystemRoles.GetPrivilegesByRoleId(RequestBase.GetFormString("ajaxroleid"));
        string xmlTemplete = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<callcenter_response>\n{0}</callcenter_response>\n";
        string xmlResponse = "";
        if (dat != null)
            foreach (DataRow dr in dat.Select(""))
            {
                xmlResponse += "<privilegeslist>\n<privilegeid>" + dr["PrivilegeId"].ToString() + "</privilegeid>\n<depthmask>" + dr["PrivilegeDepthMask"].ToString() + "</depthmask>\n</privilegeslist>\n";
            }
        BLL.AjaxHelper.ResponseWriteXML(string.Format(xmlTemplete, xmlResponse));
    }
    #endregion

    #region 角色信息管理
    /// <summary>
    /// 角色信息初始化
    /// </summary>
    void InitializeRoleInfo()
    {
        RoleInfo = BLL.SystemRoles.GetObjById(RequestBase.GetQueryString("roleid"));
        spanRoleName.InnerHtml = RoleInfo.RoleName;
    }
    /// <summary>
    /// 保存信息
    /// </summary>
    /// <returns></returns>
    string SaveRolesInfo()
    {
        string result = "";
        if (RequestBase.GetQueryString("otype") == "modify")
        {
            result = BLL.SystemRoles.Modify(RoleInfo);
        }
        if (RequestBase.GetQueryString("otype") == "add")
        {
            result = BLL.SystemRoles.Add(RoleInfo);
        }
        return result;
    }
    /// <summary>
    /// 角色实体访问器
    /// </summary>
    Model.SystemRoleBase RoleInfo
    {
        get
        {
            Model.SystemRoleBase _role = new Model.SystemRoleBase();
            _role.RoleId = RequestBase.GetQueryString("roleid").Trim();
            _role.RoleName = txtRoleName.Value.Trim();
            _role.LoweredRoleName = txtRoleName.Value.ToLower().Trim();
            _role.IsProtected = 0;
            _role.Description = txtDescription.Value.Trim();
            _role.LineNum = int.Parse(txtLineNum.Value.Trim());
            _role.IsLockout = int.Parse(selIsLockout.Value.Trim());
            _role.Organization = "";

            return _role;
        }
        set
        {
            if (value != null)
            {
                txtRoleName.Value = value.RoleName.Trim();
                txtDescription.Value = value.Description.Trim();
                txtLineNum.Value = value.LineNum.ToString();
                selIsLockout.Value = value.IsLockout.ToString();
            }
        }
    }
    #endregion
}
